import React, { useState, useEffect, useRef, forwardRef } from 'react';
import { MoreVertical, Download, Trash2, User } from 'lucide-react';
import { useApp } from '../../../contexts/AppContext';
import { TabManager } from '../utils/TabManager';

interface BrowserTabProps {
  tabId: string;
  url: string;
  title: string;
  isActive: boolean;
  accountId?: string;
  onClose: (tabId: string) => void;
  onSwitch: (tabId: string) => void;
  onUrlChange: (tabId: string, url: string) => void;
}

const tabManager = new TabManager();

export const BrowserTab = forwardRef<HTMLIFrameElement, BrowserTabProps>(function BrowserTab({
  tabId,
  url,
  title,
  isActive,
  accountId,
  onClose,
  onSwitch,
  onUrlChange
}, ref) {
  const { state, dispatch } = useApp();
  const [showMenu, setShowMenu] = useState(false);
  const [currentUrl, setCurrentUrl] = useState(url);
  const [isLoading, setIsLoading] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);

  // 初始化标签页会话
  useEffect(() => {
    const session = tabManager.getSession(tabId);
    if (!session) {
      const account = state.accounts.find(acc => acc.id === accountId);
      tabManager.createSession(tabId, {
        accountId,
        platform: account?.platform,
        initialUrl: url
      });
    }
  }, [tabId, accountId, url, state.accounts]);

  // 处理点击外部关闭菜单
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setShowMenu(false);
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  // 处理iframe加载
  const handleIframeLoad = () => {
    setIsLoading(false);
    tabManager.updateSessionActivity(tabId);
    
    // 更新标签页标题
    const iframe = iframeRef.current;
    if (iframe && iframe.contentDocument) {
      const newTitle = iframe.contentDocument.title || '无标题';
      if (newTitle !== title) {
        // 这里应该更新标签页标题
      }
    }
  };

  // 导出Cookie
  const handleExportCookies = () => {
    const cookiesJson = tabManager.exportCookies(tabId);
    const blob = new Blob([cookiesJson], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `cookies_${tabId}_${Date.now()}.json`;
    a.click();
    URL.revokeObjectURL(url);
    setShowMenu(false);
  };

  // 清除Cookie
  const handleClearCookies = () => {
    tabManager.clearCookies(tabId);
    // 重新加载页面以应用新的Cookie状态
    if (iframeRef.current) {
      iframeRef.current.src = iframeRef.current.src;
    }
    setShowMenu(false);
  };

  // 获取关联的账号信息
  const getAccountInfo = () => {
    if (!accountId) return null;
    return state.accounts.find(acc => acc.id === accountId);
  };

  const account = getAccountInfo();

  return (
    <div className={`relative w-full h-full ${isActive ? 'block' : 'hidden'}`}>
      {/* 标签页信息栏 */}
      <div className="flex items-center justify-between bg-gray-100 border-b border-gray-200 px-4 py-2">
        <div className="flex items-center space-x-2">
          {account && (
            <div className="flex items-center space-x-1 text-sm text-gray-600">
              <User size={14} />
              <span>{account.username}</span>
              <span className="text-gray-400">({account.platform})</span>
            </div>
          )}
          
          {isLoading && (
            <div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500"></div>
          )}
        </div>

        <div className="relative">
          <button
            onClick={() => setShowMenu(!showMenu)}
            className="p-1 text-gray-600 hover:bg-gray-200 rounded"
            title="标签页选项"
          >
            <MoreVertical size={16} />
          </button>

          {showMenu && (
            <div
              ref={menuRef}
              className="absolute right-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded shadow-lg z-10"
            >
              <button
                onClick={handleExportCookies}
                className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100"
              >
                <Download size={14} className="mr-2" />
                导出Cookie
              </button>
              <button
                onClick={handleClearCookies}
                className="flex items-center w-full px-3 py-2 text-sm text-left hover:bg-gray-100 text-red-600"
              >
                <Trash2 size={14} className="mr-2" />
                清除Cookie
              </button>
            </div>
          )}
        </div>
      </div>

      {/* 浏览器内容区域 */}
      <div className="w-full h-[calc(100%-40px)]">
        <iframe
          ref={iframeRef}
          src={currentUrl}
          className="w-full h-full border-0"
          onLoad={handleIframeLoad}
          onError={() => setIsLoading(false)}
          sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
          title={`标签页 ${tabId}`}
        />
      </div>
    </div>
  );
});